package com.itlong.cloud.controller.sdkV1.cloud.elevator.server;

import com.itlong.cloud.POJO.DTO.app.AppCallLiftSaveDTO;
import com.itlong.cloud.POJO.DTO.property.IotCloudElevatorStateDTO;
import com.itlong.cloud.POJO.DTO.sdk.*;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.property.AppCloudElevatorRunState;
import com.itlong.cloud.POJO.VO.sdk.CloudElevatorSDKGetByDeviceUniqueVO;
import com.itlong.cloud.POJO.VO.sdk.SDKCloudElevatorRobotRunState;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.enumerate.CallElevatorRecordSourceEnum;
import com.itlong.cloud.enumerate.CallElevatorSourceTypeEnum;
import com.itlong.cloud.enumerate.CloudElevatorCallTypeEnum;
import com.itlong.cloud.enumerate.CloudElevatorSourceEnum;
import com.itlong.cloud.enumerate.ecode.AppErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.CloudElevarotErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.SDKErrorCodeEnum;
import com.itlong.cloud.equip.app.IAppDeviceServiceClient;
import com.itlong.cloud.equip.sdk.ICloudElevatorSDKRobotClient;
import com.itlong.cloud.equip.sdk.ICloudElevatorSDKServerCloudServiceClient;
import com.itlong.cloud.project.sdk.ICloudTalkSDKServerProjectServiceClient;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.app.IAppHomeServiceClient;
import com.itlong.cloud.user.operate.IOperatePropertyAccountServiceClient;
import com.itlong.cloud.user.sdk.ICloudTalkSDKServerUserServiceClient;
import com.itlong.cloud.user.sdk.ISDKServerOldUserServiceClient;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.random.LogicIdUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <desc>
 * 云电梯SDK服务端机器人对旺龙Controller
 * </desc>
 *
 * @createDate 2018/12/27
 */
@RestController
@RequestMapping("/cloud/elevator/rtl")
public class CloudElevatorSDKRobotBaseController {


    private static final Logger LOG = LoggerFactory.getLogger(CloudElevatorSDKRobotBaseController.class);

    @Autowired
    ICloudElevatorSDKRobotClient iCloudElevatorSDKRobotServiceClient;

    @Autowired
    private ICloudElevatorSDKServerCloudServiceClient iCloudElevatorSDKServerCloudServiceClient;

    @Autowired
    IAppDeviceServiceClient iAppDeviceServiceClient;

    @Autowired
    ICloudTalkSDKServerUserServiceClient iCloudTalkSDKServerUserServiceClient;

    @Autowired
    IOperatePropertyAccountServiceClient iOperatePropertyAccountServiceClient;

    @Autowired
    ISDKServerOldUserServiceClient iSDKServerUserServiceClient;

    @Autowired
    IAppHomeServiceClient iAppHomeServiceClient;

    @Autowired
    RedisService redisService;

    @Autowired
    private ICloudTalkSDKServerProjectServiceClient iCloudTalkSDKServerProjectServiceClient;


    /**
     * <desc>
     * 查询唯一标识
     * <desc/>
     *
     * @return Object   标准格式化响应结果
     * @author Qiang.S
     * @createDate 2018/12/27
     */
    @ResponseBody
    @PostMapping("/getElevatorKey")
    //@LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_GET_ELEVATOR_DEVICE_UNIQUE_LOG_DESC)
    public Object getElevatorKey() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            CloudElevatorSDKServerElevatorKeyDTO cloudElevatorSDKServerElevatorKeyDTO =
                    HttpProtocolUtil.parseRequestParamToDTO(CloudElevatorSDKServerElevatorKeyDTO.class, request);

            if (StringUtils.isEmpty(cloudElevatorSDKServerElevatorKeyDTO.getRobotId()) || StringUtils.isEmpty(cloudElevatorSDKServerElevatorKeyDTO.getProjectId())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            //验证机器人是否有权限
            if (iCloudTalkSDKServerUserServiceClient.checkRobot(cloudElevatorSDKServerElevatorKeyDTO.getAppId(),cloudElevatorSDKServerElevatorKeyDTO.getAppSecret(),cloudElevatorSDKServerElevatorKeyDTO.getRobotId()) == 0) {
                return new MessageVO(CloudElevarotErrorCodeEnum.ROBOT_AUTH_ERROR.getErrorCode());
            }
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark",cloudElevatorSDKServerElevatorKeyDTO.getProjectId() + "查询项目下电梯设备唯一码列表");
            request.setAttribute("portType",LogDescConstant.SDK_CLOUD_ELEVATOR_TYPE_LOG_DESC);
            List<String> list = iCloudElevatorSDKRobotServiceClient.getElevatorKey(cloudElevatorSDKServerElevatorKeyDTO);
            List<Map<String, String>> allList = new ArrayList<>();
            if (list.size()!=0) {
                list.forEach(str -> {
                    Map<String, String> map = new HashMap<>();
                    map.put("deviceUnique", str);
                    allList.add(map);
                });
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),allList);
        } catch (Exception e) {
            throw new DataAccessException("【云对讲SDK服务端_SDKgetElevatorKey】查询唯一标识异常", e);
        }
    }

    /**
     * <desc>
     *      根据设备唯一码查询电梯信息
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/12/28
     */
    @ResponseBody
    @PostMapping("/getElevatorInfo")
    //@LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_GET_ELEVATOR_INFO_LOG_DESC)
    public Object getElevatorInfo(){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            CloudElevatorSDKGetByDeviceUniqueDTO cloudElevatorSDKGetByDeviceUniqueDTO = HttpProtocolUtil.parseRequestParamToDTO(CloudElevatorSDKGetByDeviceUniqueDTO.class, request);

            if (StringUtils.isBlank(cloudElevatorSDKGetByDeviceUniqueDTO.getDeviceUnique())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            CloudElevatorSDKServerElevatorKeyDTO cloudElevatorSDKServerElevatorKeyDTO = new CloudElevatorSDKServerElevatorKeyDTO();
            cloudElevatorSDKServerElevatorKeyDTO.setProjectId(cloudElevatorSDKGetByDeviceUniqueDTO.getProjectId());
            cloudElevatorSDKServerElevatorKeyDTO.setAppId(cloudElevatorSDKGetByDeviceUniqueDTO.getAppId());
            cloudElevatorSDKServerElevatorKeyDTO.setRoleId(cloudElevatorSDKGetByDeviceUniqueDTO.getRoleId());
            List<String> deviceUniques = iCloudElevatorSDKRobotServiceClient.getElevatorKey(cloudElevatorSDKServerElevatorKeyDTO);
            if (deviceUniques == null || deviceUniques.isEmpty()) {
                return new MessageVO(SDKErrorCodeEnum.SDK_SERVER_NO_DEVICE_UNIQUE_ERR.getErrorCode());
            }else  {
                //判断入参中deviceUnique中是否全部包含查询出的结果
                for (String deviceUniqueAuth:cloudElevatorSDKGetByDeviceUniqueDTO.getDeviceUnique().split(",")) {
                    int flag = 0;
                    for (String deviceUnique:deviceUniques) {
                        if (deviceUnique.equals(deviceUniqueAuth)) {
                            flag = 1;
                            break;
                        }
                    }
                    if (flag == 0) {
                        return new MessageVO(SDKErrorCodeEnum.SDK_SERVER_NO_DEVICE_UNIQUE_ERR.getErrorCode());
                    }
                }
            }
            //验证机器人是否有权限
            if (iCloudTalkSDKServerUserServiceClient.checkRobot(cloudElevatorSDKGetByDeviceUniqueDTO.getAppId(),cloudElevatorSDKGetByDeviceUniqueDTO.getAppSecret(),cloudElevatorSDKGetByDeviceUniqueDTO.getRobotId()) == 0) {
                return new MessageVO(CloudElevarotErrorCodeEnum.ROBOT_AUTH_ERROR.getErrorCode());
            }
            List<CloudElevatorSDKGetByDeviceUniqueVO> cloudElevatorSDKGetByDeviceUniqueVOS = iCloudElevatorSDKServerCloudServiceClient.getElevatorInfo(cloudElevatorSDKGetByDeviceUniqueDTO);
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark",cloudElevatorSDKGetByDeviceUniqueDTO.getProjectId() + "根据设备唯一码" + cloudElevatorSDKGetByDeviceUniqueDTO.getDeviceUnique() + "查询电梯信息");
            request.setAttribute("portType",LogDescConstant.SDK_CLOUD_ELEVATOR_TYPE_LOG_DESC);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),cloudElevatorSDKGetByDeviceUniqueVOS);
        } catch (Exception e) {
            throw new DataAccessException("【云电梯SDK_服务端_根据设备唯一码查询电梯信息】根据设备唯一码查询电梯信息失败",e);
        }
    }

    /**
     * <desc>
     *      获取电梯时时状态。
     * <desc/>
     *
     * @return
     * @author Qiang.S
     * @createDate 2018-12-29
     */
    @RequestMapping(value = "/getElevatorOftenStatus",method = RequestMethod.POST)
//    @LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_GET_ELEVATORINFO_LOG_DESC)
    @ResponseBody
    public Object getElevatorOftenStatus(){
        MessageVO messageVO;
        try{
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            CloudElevatorSDKGetByDeviceUniqueDTO cloudElevatorSDKGetByDeviceUniqueDTO = HttpProtocolUtil.parseRequestParamToDTO(CloudElevatorSDKGetByDeviceUniqueDTO.class, request);

            if (StringUtils.isBlank(cloudElevatorSDKGetByDeviceUniqueDTO.getDeviceUnique())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }

            //获取设备编号列表
            String[]  deviceUniqueArr = StringHandlerUtil.splitString(cloudElevatorSDKGetByDeviceUniqueDTO.getDeviceUnique());
            if((deviceUniqueArr==null)||(deviceUniqueArr.length<1)){
                return new MessageVO(AppErrorCodeEnum.DEVICE_UNIQUE_EMPTY_ERR.getErrorCode());
            }
            //验证机器人是否有权限
            if (iCloudTalkSDKServerUserServiceClient.checkRobot(cloudElevatorSDKGetByDeviceUniqueDTO.getAppId(),cloudElevatorSDKGetByDeviceUniqueDTO.getAppSecret(),cloudElevatorSDKGetByDeviceUniqueDTO.getRobotId()) == 0) {
                return new MessageVO(CloudElevarotErrorCodeEnum.ROBOT_AUTH_ERROR.getErrorCode());
            }
            List<AppCloudElevatorRunState> eleRunStatesVO = iAppDeviceServiceClient.getCloudElevatorState(cloudElevatorSDKGetByDeviceUniqueDTO.getDeviceUnique(),
                    cloudElevatorSDKGetByDeviceUniqueDTO.getRobotId());
            List<SDKCloudElevatorRobotRunState>  list = new ArrayList<>();
            for (AppCloudElevatorRunState appCloudElevatorRunState:eleRunStatesVO) {
                SDKCloudElevatorRobotRunState sdkCloudElevatorRobotRunState = new SDKCloudElevatorRobotRunState();
                sdkCloudElevatorRobotRunState.setCodeName(appCloudElevatorRunState.getCodeName());
                sdkCloudElevatorRobotRunState.setDeviceUnique(appCloudElevatorRunState.getDeviceUnique());
                sdkCloudElevatorRobotRunState.setFloorNum(appCloudElevatorRunState.getFloorNum());
                sdkCloudElevatorRobotRunState.setLiftState(appCloudElevatorRunState.getLiftState());
                sdkCloudElevatorRobotRunState.setDoorStatus(appCloudElevatorRunState.getDoorStatus());
                sdkCloudElevatorRobotRunState.setTimestamp(appCloudElevatorRunState.getTimestamp());
                list.add(sdkCloudElevatorRobotRunState);
            }
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark","根据设备唯一码" + cloudElevatorSDKGetByDeviceUniqueDTO.getDeviceUnique() + "查询电梯状态");
            request.setAttribute("portType",LogDescConstant.SDK_CLOUD_ELEVATOR_TYPE_LOG_DESC);
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),list);
        }catch (Exception e){
            throw new DataAccessException("【云电梯SDK_服务端_根据设备唯一码查询电梯状态】根据设备唯一码查询电梯状态失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      呼叫电梯
     * <desc/>
     *
     * @return
     * @author Jiaqi.X
     * @createDate 2019-01-03
     */
    @RequestMapping(value = "/callElevator",method = RequestMethod.POST)
    @LoggerInfo(operateDesc = LogDescConstant.SDK_ROBOT_CALL_ELEVATOR)
    @ResponseBody
    public Object callElevator() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            CloudElevatorSDKCallElevatorDTO cloudElevatorSDKCallElevatorDTO =
                    HttpProtocolUtil.parseRequestParamToDTO(CloudElevatorSDKCallElevatorDTO.class, request);
            if (StringUtils.isEmpty(cloudElevatorSDKCallElevatorDTO.getProjectId())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isEmpty(cloudElevatorSDKCallElevatorDTO.getFromFloor())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isEmpty(cloudElevatorSDKCallElevatorDTO.getToFloor())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isEmpty(cloudElevatorSDKCallElevatorDTO.getDeviceUnique())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            //获取真实楼层
            Map<String,Object> floor = iCloudElevatorSDKServerCloudServiceClient.getFloorNumByLogicFloor(cloudElevatorSDKCallElevatorDTO.getFromFloor(),
                    cloudElevatorSDKCallElevatorDTO.getToFloor(),cloudElevatorSDKCallElevatorDTO.getDeviceUnique());
            if(floor == null || floor.get("goFloor") == null || floor.get("fromFloor") == null){
                return new MessageVO(CloudElevarotErrorCodeEnum.CLOUD_FLOOR_ERROR.getErrorCode());
            }
            //调用IOT呼梯
            iAppDeviceServiceClient.cloudElevatorCall(cloudElevatorSDKCallElevatorDTO.getDeviceUnique(),
                    CloudElevatorSourceEnum.ITLONG_CLOUD_ELEVATOR.getDescription(),
                    floor.get("goFloor").toString(),floor.get("fromFloor").toString(),null,
                    CloudElevatorCallTypeEnum.OUT.getType(),null,CallElevatorSourceTypeEnum.ROBOT.getType(),
                    cloudElevatorSDKCallElevatorDTO.getRobotId(),null,cloudElevatorSDKCallElevatorDTO.getCtrElevator(), null, null, null, "");
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark",cloudElevatorSDKCallElevatorDTO.getProjectId() + "呼叫电梯");
            request.setAttribute("portType",LogDescConstant.SDK_CLOUD_ELEVATOR_TYPE_LOG_DESC);
            //装配呼梯记录对象
            AppCallLiftSaveDTO saveDTO = new AppCallLiftSaveDTO();
            saveDTO.setDeviceUnique(cloudElevatorSDKCallElevatorDTO.getDeviceUnique());
            saveDTO.setFromFloor(cloudElevatorSDKCallElevatorDTO.getFromFloor());
            saveDTO.setToFloor(cloudElevatorSDKCallElevatorDTO.getToFloor());
            saveDTO.setProjectId(cloudElevatorSDKCallElevatorDTO.getProjectId());
            saveDTO.setSource(CallElevatorRecordSourceEnum.ROBOT.getType());
            saveDTO.setUserId(cloudElevatorSDKCallElevatorDTO.getRobotId());
            iAppHomeServiceClient.saveCallLiftRecord(saveDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【云对讲SDK服务端_SDKgetElevatorKey】呼叫电梯异常", e);
        }
    }

    /**
     * <desc>
     *      电梯楼层开放或登记
     * <desc/>
     *
     * @return
     * @author Jiaqi.X
     * @createDate 2019/08/15
     */
    @RequestMapping(value = "/openOrAutoRegister",method = RequestMethod.POST)
    @LoggerInfo(operateDesc = LogDescConstant.SDK_ROBOT_CALL_ELEVATOR)
    @ResponseBody
    public Object openOrAutoRegister() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            CloudElevatorSDKOpenOrAutoRegisterDTO cloudElevatorSDKOpenOrAutoRegisterDTO =
                    HttpProtocolUtil.parseRequestParamToDTO(CloudElevatorSDKOpenOrAutoRegisterDTO.class, request);
            if (StringUtils.isEmpty(cloudElevatorSDKOpenOrAutoRegisterDTO.getProjectId())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            //获取真实楼层
            Map<String,Object> floor = iCloudElevatorSDKServerCloudServiceClient.getFloorNumAndNaturalFloorByLogicFloor(cloudElevatorSDKOpenOrAutoRegisterDTO.getFloors(),
                    cloudElevatorSDKOpenOrAutoRegisterDTO.getDeviceUnique());
            if(floor ==null || floor.get("floors") ==null || floor.get("naturals") == null){
                return new MessageVO(CloudElevarotErrorCodeEnum.CLOUD_FLOOR_ERROR.getErrorCode());
            }
            //调用IOT呼梯
            iAppDeviceServiceClient.openOrAutoRegister(cloudElevatorSDKOpenOrAutoRegisterDTO.getDeviceUnique(),
                    CloudElevatorSourceEnum.ITLONG_CLOUD_ELEVATOR.getDescription(),
                    floor.get("floors").toString(),  CloudElevatorCallTypeEnum.IN.getType(),cloudElevatorSDKOpenOrAutoRegisterDTO.getSeconds(), CallElevatorSourceTypeEnum.ROBOT.getType(),"1", null);
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark",cloudElevatorSDKOpenOrAutoRegisterDTO.getProjectId() + "开放或登记楼层");
            request.setAttribute("portType",LogDescConstant.SDK_CLOUD_ELEVATOR_TYPE_LOG_DESC);
            //装配呼梯记录对象
            AppCallLiftSaveDTO saveDTO = new AppCallLiftSaveDTO();
            saveDTO.setDeviceUnique(cloudElevatorSDKOpenOrAutoRegisterDTO.getDeviceUnique());
            saveDTO.setToFloor(floor.get("naturals").toString());
            saveDTO.setProjectId(cloudElevatorSDKOpenOrAutoRegisterDTO.getProjectId());
            saveDTO.setSource(CallElevatorRecordSourceEnum.ROBOT.getType());
            saveDTO.setUserId(cloudElevatorSDKOpenOrAutoRegisterDTO.getAppId());
            iAppHomeServiceClient.saveCallLiftRecord(saveDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【云电梯SDK服务端_SDKgetElevatorKey】呼叫电梯异常", e);
        }
    }

    /**
     * <desc>
     *      发送开门关门指令
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author Juguang.S
     * @createDate 2018/12/28
     */
    @ResponseBody
    @PostMapping("/sendOpenAndCloseDoor")
    @LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_SEND_OPEN_CLOSE_DOOR_LOG_DESC)
    public Object sendOpenAndCloseDoor() {
        try {
            String snr = LogicIdUtil.bussinessId();
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            CloudElevatorSDKServerSendCommandDTO cloudElevatorSDKServerSendCommandDTO = HttpProtocolUtil.parseRequestParamToDTO(CloudElevatorSDKServerSendCommandDTO.class, request);
            Integer effectiveTime = cloudElevatorSDKServerSendCommandDTO.getEffectiveTime();
            if(effectiveTime == null){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (effectiveTime < 0 || effectiveTime > 99) {
                return new MessageVO(SDKErrorCodeEnum.SDK_SERVER_EFFECTIVE_TIME_OUT_ERR.getErrorCode());
            }

            CloudElevatorSDKServerElevatorKeyDTO cloudElevatorSDKServerElevatorKeyDTO = new CloudElevatorSDKServerElevatorKeyDTO();
            cloudElevatorSDKServerElevatorKeyDTO.setProjectId(cloudElevatorSDKServerSendCommandDTO.getProjectId());
            cloudElevatorSDKServerElevatorKeyDTO.setAppId(cloudElevatorSDKServerSendCommandDTO.getAppId());
            cloudElevatorSDKServerElevatorKeyDTO.setRoleId(cloudElevatorSDKServerSendCommandDTO.getRoleId());
            List<String> deviceUniques = iCloudElevatorSDKRobotServiceClient.getElevatorKey(cloudElevatorSDKServerElevatorKeyDTO);
            if (deviceUniques == null || deviceUniques.isEmpty() || !deviceUniques.contains(cloudElevatorSDKServerSendCommandDTO.getDeviceUnique())) {
                return new MessageVO(SDKErrorCodeEnum.SDK_SERVER_NO_DEVICE_UNIQUE_ERR.getErrorCode());
            }

            if (cloudElevatorSDKServerSendCommandDTO.getType() == 1) {
                iAppDeviceServiceClient.cloudElevatorCall(cloudElevatorSDKServerSendCommandDTO.getDeviceUnique(),
                        CloudElevatorSourceEnum.ITLONG_CLOUD_ELEVATOR.getDescription(),
                        null, null, null, CloudElevatorCallTypeEnum.OPEN.getType(), effectiveTime,CallElevatorSourceTypeEnum.ROBOT.getType(),null,snr,null, 1, cloudElevatorSDKServerSendCommandDTO.getUpDown(), null, "");
            }
            if (cloudElevatorSDKServerSendCommandDTO.getType() == 2) {
                iAppDeviceServiceClient.cloudElevatorCall(cloudElevatorSDKServerSendCommandDTO.getDeviceUnique(),
                        CloudElevatorSourceEnum.ITLONG_CLOUD_ELEVATOR.getDescription(),
                        null, null, null, CloudElevatorCallTypeEnum.CLOSE.getType(), effectiveTime,CallElevatorSourceTypeEnum.ROBOT.getType(),null,snr,null, null, cloudElevatorSDKServerSendCommandDTO.getUpDown(), null, "");
            }
            //判断电梯当前状态是否是开门，如果是开门则返回成功，否则返回失败
            boolean isOpen = false;
            int count = 0;
            while (count < 5) {
                Thread.sleep(900);
                if (isDeviceExecute(snr)) {
                    isOpen = true;
                    break;
                }
                count++;
            }
            /*
            while(count<10){
                Thread.sleep(500);
                IotCloudElevatorStateDTO dto = JsonUtil.toObject(redisService.getKeysForDevice(RedisConstant.REDIS_IOT_CLOUD_ELEVATOR_STATE_CACHE +
                        cloudElevatorSDKServerSendCommandDTO.getDeviceUnique()),IotCloudElevatorStateDTO.class);
                if(dto != null && StringUtils.isNotBlank(dto.getFrontDoor()) && (dto.getFrontDoor().equals("1") ||
                        dto.getFrontDoor().equals("3") || dto.getFrontDoor().equals("4"))){
                    isOpen = true;
                    break;
                }else{
                    //如从缓存中读取不到电梯的信息触发iot发送电梯控制指令
                    iAppDeviceServiceClient.getCloudElevatorState(cloudElevatorSDKServerSendCommandDTO.getDeviceUnique(), "");
                }
                count++;
            }
             */
            Map<String,Object> result = new HashMap<>();
            result.put("isOpen",isOpen+"");
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark", String.format("%s%s%s", "设备唯一码：", cloudElevatorSDKServerSendCommandDTO.getDeviceUnique(), LogDescConstant.SDK_SERVER_SEND_OPEN_CLOSE_DOOR_LOG_DESC));
            request.setAttribute("portType", LogDescConstant.SDK_CLOUD_ELEVATOR_TYPE_LOG_DESC);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),result);
        } catch (Exception e) {
            throw new DataAccessException("【云电梯SDK_服务端】发送开门关门指令失败", e);
        }
    }

    /**
     * <desc>
     *      设置专梯模式
     * <desc/>
     *
     * @return
     * @author Jiaqi.X
     * @createDate 2019-01-03
     */
    @RequestMapping(value = "/setCloudElevatorSpecialUseModel",method = RequestMethod.POST)
    @LoggerInfo(operateDesc = LogDescConstant.SDK_ROBOT_SET_CLOUD_ELEVATOR_SPECIAL_USE_MODEL)
    @ResponseBody
    public Object setCloudElevatorSpecialUseModel() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            CloudElevatorSDKSpecialUseModelDTO cloudElevatorSDKSpecialUseModelDTO =
                    HttpProtocolUtil.parseRequestParamToDTO(CloudElevatorSDKSpecialUseModelDTO.class, request);
            if (StringUtils.isEmpty(cloudElevatorSDKSpecialUseModelDTO.getProjectId())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            iAppDeviceServiceClient.setCloudElevatorSpecialUseModel(cloudElevatorSDKSpecialUseModelDTO.getDeviceUnique(),cloudElevatorSDKSpecialUseModelDTO.getModel());
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark",cloudElevatorSDKSpecialUseModelDTO.getProjectId() + "设置专梯模式");
            request.setAttribute("portType",LogDescConstant.SDK_CLOUD_ELEVATOR_TYPE_LOG_DESC);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【云对讲SDK服务端_SDKgetElevatorKey】设置专梯模式异常", e);
        }
    }

    private boolean isDeviceExecute(String snr) {
        String ali = redisService.get(RedisConstant.REDIS_IOT_DEVICE_HANDLE_RESULT_CACHE + "_ali_" + snr);
        String hw = redisService.get(RedisConstant.REDIS_IOT_DEVICE_HANDLE_RESULT_CACHE + "_hw_" + snr);
        boolean b1 = (ali != null && !ali.equals(""));
        boolean b2 = (hw != null && !hw.equals(""));
        if (b1 || b2) {
            return true;
        }
        return false;
    }
}